﻿using adb;
using Masuit.Tools;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using PowerStation.RequestModel;
using PowerStation.TableModel;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using utils;
using Z.EntityFramework.Plus;

namespace PowerStation.Controllers
{
    /// <summary>
    /// 数据统计管理
    /// </summary>
    public class StatisticsController : BaseApi<AlarmController>
    {
        private readonly RedisUtil _redisUtil;

        /// <summary>
        /// 数据统计管理
        /// </summary>
        /// <param name="content"></param>
        public StatisticsController(IHttpContextAccessor content, RedisUtil redisUtil) : base(content)
        {
            this._redisUtil = redisUtil;
        }


        /// <summary>
        /// 按片区反回电站
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<vPowerStation>>> AreaPowerStationList(decimal keyId)
        {
            IQueryable<vPowerStation> q = this._db.vPowerStation.Where(x => x.powerStationArea_keyId_fk == keyId);
            return ResultApi.ok<List<vPowerStation>>(await q.ToListAsync());
        }


        /// <summary>
        /// 获取我自己绑定的电站列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<ResponsePowerStation>>> MinePowerStationList(string powerStationName = null)
        {
            //IQueryable<vPowerStation> q = this._db.vPowerStation.Join(this._db.tUserPowerStation.Where(x => x.ups_user_userId_fk == this.userId), x => x.powerStationId, k => k.ups_powerStation_powerStationId_fk, (x, k) => x);

            var q = from p in this._db.tPowerStation
                    join c in this._db.tKey on p.powerStationCity_keyId_fk equals c.keyId into city
                    from c in city.DefaultIfEmpty()
                    join pt in this._db.tKey on p.powerStationType_keyId_fk equals pt.keyId into ptype
                    from pt in ptype.DefaultIfEmpty()
                    join d in this._db.tKey on p.powerStationDrainageArea_keyId_fk equals d.keyId into drainage
                    from d in drainage.DefaultIfEmpty()
                    join a in this._db.tKey on p.powerStationArea_keyId_fk equals a.keyId into area
                    from a in area.DefaultIfEmpty()
                    join sn in this._db.tDevice on p.powerStationId equals sn.station_device_powerStationId_fk into deviceSN
                    from sn in deviceSN.DefaultIfEmpty()
                    join xian in this._db.tKey on (long)p.powerStationXianId equals xian.keyId into xianName
                    from xian in xianName.DefaultIfEmpty()
                    join sheng in this._db.tKey on (long)p.powerStationShengId equals sheng.keyId into shengName
                    from sheng in shengName.DefaultIfEmpty()
                    select new ResponsePowerStation
                    {
                        powerStationXianId = p.powerStationXianId,
                        powerStationShengId = p.powerStationShengId,
                        powerStationArea_keyId_fk = p.powerStationArea_keyId_fk,
                        powerStationId = p.powerStationId,
                        powerStationCity_keyId_fk = p.powerStationCity_keyId_fk,
                        powerStationDrainageArea_keyId_fk = p.powerStationDrainageArea_keyId_fk,
                        powerStationName = p.powerStationName,
                        powerStationNo = p.powerStationNo,
                        powerStationType_keyId_fk = p.powerStationType_keyId_fk,
                        progress_keyId_fk = p.progress_keyId_fk,
                        upPrice = p.upPrice,
                        companyDes = p.companyDes,
                        companyName = p.companyName,
                        securityDay = p.securityDay,
                        sort = p.sort,
                        dataState = p.dataState,
                        addTime = p.addTime,
                        cityName = c.keyName,
                        xianName = xian.keyName,
                        shengName = sheng.keyName,
                        powerStationTypeName = pt.keyName,
                        drainageName = d.keyName,
                        keyName = a.keyName,
                        deviceSN = sn.deviceSN,
                        powerRate = p.powerRate,
                        salePowerRate = p.salePowerRate
                    };

            
            if (!string.IsNullOrEmpty(powerStationName))
            {
                q = q.Where(x => x.powerStationName.Contains(powerStationName));
            }
            
            q = q.Where(x => (from up in this._db.tUserPowerStation
                              where up.ups_powerStation_powerStationId_fk == x.powerStationId && up.ups_user_userId_fk == this.userId
                              select up.ups_powerStation_powerStationId_fk
                         ).Any());
            var lst = await q.ToListAsync();
            foreach (var item in lst)
            {
                item.MessageNotReadCount = await this._db.tMessage.Where(x => x.messageOfPowerStation_powerStationId_fk == item.powerStationId && x.messageOfUser_userId_fk == this.userId && x.isRead == false).CountAsync();
            }
            return ResultApi.ok<List<ResponsePowerStation>>(lst, lst.Count);
        }


        /// <summary>
        /// 中心门户-生产管理-统计分析接口数据,返回当月头部数据
        /// </summary>
        /// <param name="keyType">1按片区统计,2按电站统计</param>
        /// <param name="keyIdOrPowerStationId">按片区就传片区ID,按电站就填写电站ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<RequestStatisticsModel>>> StatisticsCenterTopDataList(long? keyIdOrPowerStationId,int? keyType)
        {
            var powerModel = new RequestStatisticsModel { 
                title = "发电量",
                value = 0
            };
            var salseModel = new RequestStatisticsModel
            {
                title = "上网电量",
                value = 0
            };
            var planModel = new RequestStatisticsModel
            {
                title = "计划发电量",
                value = 0
            };
            var useModel = new RequestStatisticsModel
            {
                title = "厂用电量",
                value = 0
            };
            var powerModel1 = new RequestStatisticsModel
            {
                title = "去年发电量",
                value = 0
            };
            var salseModel1 = new RequestStatisticsModel
            {
                title = "去年上网电量",
                value = 0
            };
            var planModel1 = new RequestStatisticsModel
            {
                title = "去年计划发电量",
                value = 0
            };
            var useModel1 = new RequestStatisticsModel
            {
                title = "去年厂用电量",
                value = 0
            };
            if (keyType.HasValue && keyIdOrPowerStationId.HasValue && keyType == 1)
            {
                powerModel.value = await DataCache.PowerData.MonthValue(DateTime.Now,0,keyIdOrPowerStationId.Value);
                salseModel.value = await DataCache.SalesData.MonthValue(DateTime.Now, 0, keyIdOrPowerStationId.Value);
                planModel.value = await DataCache.PlanDataOfMonth.MonthValue(DateTime.Now, 0, keyIdOrPowerStationId.Value);
                useModel.value = await DataCache.FactoryUsePower.MonthValue(DateTime.Now, 0, keyIdOrPowerStationId.Value);

                powerModel1.value = await DataCache.PowerData.MonthValue(DateTime.Now.AddYears(-1), 0, keyIdOrPowerStationId.Value);
                salseModel1.value = await DataCache.SalesData.MonthValue(DateTime.Now.AddYears(-1), 0, keyIdOrPowerStationId.Value);
                planModel1.value = await DataCache.PlanDataOfMonth.MonthValue(DateTime.Now.AddYears(-1), 0, keyIdOrPowerStationId.Value);
                useModel1.value = await DataCache.FactoryUsePower.MonthValue(DateTime.Now.AddYears(-1), 0, keyIdOrPowerStationId.Value);
            }
            else if (keyType.HasValue && keyIdOrPowerStationId.HasValue && keyType == 2)
            {
                powerModel.value = await DataCache.PowerData.MonthValue(DateTime.Now,  keyIdOrPowerStationId.Value);
                salseModel.value = await DataCache.SalesData.MonthValue(DateTime.Now,  keyIdOrPowerStationId.Value);
                planModel.value = await DataCache.PlanDataOfMonth.MonthValue(DateTime.Now,  keyIdOrPowerStationId.Value);
                useModel.value = await DataCache.FactoryUsePower.MonthValue(DateTime.Now, keyIdOrPowerStationId.Value);

                powerModel1.value = await DataCache.PowerData.MonthValue(DateTime.Now.AddYears(-1),  keyIdOrPowerStationId.Value);
                salseModel1.value = await DataCache.SalesData.MonthValue(DateTime.Now.AddYears(-1),  keyIdOrPowerStationId.Value);
                planModel1.value = await DataCache.PlanDataOfMonth.MonthValue(DateTime.Now.AddYears(-1),  keyIdOrPowerStationId.Value);
                useModel1.value = await DataCache.FactoryUsePower.MonthValue(DateTime.Now.AddYears(-1), keyIdOrPowerStationId.Value);
            }
            else {
                powerModel.value = await DataCache.PowerData.MonthValue(DateTime.Now);
                salseModel.value = await DataCache.SalesData.MonthValue(DateTime.Now);
                planModel.value = await DataCache.PlanDataOfMonth.MonthValue(DateTime.Now);
                useModel.value = await DataCache.FactoryUsePower.MonthValue(DateTime.Now);

                powerModel1.value = await DataCache.PowerData.MonthValue(DateTime.Now.AddYears(-1));
                salseModel1.value = await DataCache.SalesData.MonthValue(DateTime.Now.AddYears(-1));
                planModel1.value = await DataCache.PlanDataOfMonth.MonthValue(DateTime.Now.AddYears(-1));
                useModel1.value = await DataCache.FactoryUsePower.MonthValue(DateTime.Now.AddYears(-1));
            }
            return ResultApi.ok<List<RequestStatisticsModel>>(new List<RequestStatisticsModel>() { salseModel ,powerModel,planModel, useModel,salseModel1, powerModel1, planModel1, useModel1 }, 0);
        }


        /// <summary>
        /// 中心门户-生产管理-统计分析接口数据
        /// </summary>
        /// <param name="type">统计类型,1发电量,2,预发电量,3上网电量,4厂用电量</param>
        /// <param name="timeType">时间类型,1:日,2:月,3:年</param>
        /// <param name="start">统计数据开始的时间,大于等于 start</param>
        /// <param name="end">数据统计结束时间, 小于 end</param>
        /// <param name="keyType">1按片区统计,2按电站统计</param>
        /// <param name="keyIdOrPowerStationId">按片区就传片区ID,按电站就填写电站ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<RequestStatisticsModel>>> StatisticsCenterList(int type, int timeType, DateTime start, DateTime end, long? keyIdOrPowerStationId, int? keyType)
        {
            
            if (timeType == 1 && !start.IsSameDay(end)) return ResultApi.error<List<RequestStatisticsModel>>(null,"按日查询时间跨度不能大于1天");
            long powerStationId = 0;
            long keyId = 0;
            if (keyType.HasValue && keyIdOrPowerStationId.HasValue && keyType.Value == 1)
            {
                keyId = keyIdOrPowerStationId.Value;
            }
            if (keyType.HasValue && keyIdOrPowerStationId.HasValue && keyType.Value == 2)
            {
                powerStationId = keyIdOrPowerStationId.Value;
            }
            if (timeType == 1)
            {
                Func<DateTime, Task<List<RequestStatisticsModel>>> actionFun = async (date) =>
                {
                    List<RequestStatisticsModel> lst = new List<RequestStatisticsModel>();
                    for (DateTime i = date.Date; i.IsSameDay(date); i = i.AddHours(2))
                    {
                        RequestStatisticsModel model = new RequestStatisticsModel();
                        DateTime ee = i.AddHours(2);
                        model.title = $"{i:yyyy}_{i:HH:mm}-{ee:HH:mm}";
                        if (type == 1)
                        {
                            model.value = await DataCache.PowerData.hourValue(i,ee,powerStationId,keyId);
                        }
                        else if (type == 3)
                        {
                            model.value = await DataCache.SalesData.hourValue(i,ee,powerStationId,keyId);
                        }
                        else if (type == 4)
                        {
                            model.value = await DataCache.FactoryUsePower.hourValue(i, ee, powerStationId, keyId);
                        }
                        lst.Add(model);
                    }
                    return lst;
                };
                List<RequestStatisticsModel> lst = new List<RequestStatisticsModel>();
                lst.AddRange(await actionFun(start));
                lst.AddRange(await actionFun(start.AddYears(-1)));
                return ResultApi.ok(lst);
            }
            else if (timeType == 2)
            {


                List<RequestStatisticsModel> lst = new List<RequestStatisticsModel>();

                for (DateTime i = start.Date;  i <= end; i = i.AddDays(1))
                {
                    RequestStatisticsModel model = new RequestStatisticsModel();
                    RequestStatisticsModel model1 = new RequestStatisticsModel();
                    DateTime ee = i.AddHours(2);
                    model.title = $"{i:yyyy}_{i:MM-dd}";
                    model1.title = $"{i.AddYears(-1):yyyy}_{i.AddYears(-1):MM-dd}";
                    if (type == 1)
                    {
                        model.value = await DataCache.PowerData.DayValue(i, powerStationId, keyId);
                        model1.value = await DataCache.PowerData.DayValue(i.AddYears(1), powerStationId, keyId);
                    }
                    else if (type == 3)
                    {
                        model.value = await DataCache.SalesData.DayValue(i, powerStationId, keyId);
                        model1.value = await DataCache.SalesData.DayValue(i.AddYears(-1), powerStationId, keyId);
                    }
                    else if (type == 4)
                    {
                        model.value = (await DataCache.FactoryUsePower.DayValue(i, powerStationId, keyId));
                        model1.value = (await DataCache.FactoryUsePower.DayValue(i.AddYears(-1), powerStationId, keyId));
                    }
                    lst.Add(model);
                    lst.Add(model1);
                }

                return ResultApi.ok(lst);
            }
            else {
                List<RequestStatisticsModel> lst = new List<RequestStatisticsModel>();

                for (DateTime i = start.Date; i < end; i = i.AddMonths(1))
                {
                    RequestStatisticsModel model = new RequestStatisticsModel();
                    RequestStatisticsModel model1 = new RequestStatisticsModel();
                    DateTime ee = i.AddHours(2);
                    model.title = $"{i:yyyy}_{i:MM}";
                    model1.title = $"{i.AddYears(-1):yyyy}_{i.AddYears(-1):MM}";
                    if (type == 1)
                    {
                        model.value = await DataCache.PowerData.MonthValue(i, powerStationId, keyId);
                        model1.value = await DataCache.PowerData.MonthValue(i.AddYears(1), powerStationId, keyId);
                    }
                    else if (type == 3)
                    {
                        model.value = await DataCache.SalesData.MonthValue(i, powerStationId, keyId);
                        model1.value = await DataCache.SalesData.MonthValue(i.AddYears(-1), powerStationId, keyId);
                    }
                    else if (type == 4)
                    {
                        model.value = await DataCache.FactoryUsePower.MonthValue(i, powerStationId, keyId);
                        model1.value = await DataCache.FactoryUsePower.MonthValue(i.AddYears(-1), powerStationId, keyId);
                    }
                    lst.Add(model);
                    lst.Add(model1);
                }

                return ResultApi.ok(lst);
            }

        }


        /// <summary>
        /// 中心门户-生产管理-综合信息监测
        /// </summary>
        /// <param name="date">信息日期</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<ComprehensiveInformationMonitoringModel>> ComprehensiveInformationMonitoringList(DateTime date)
        {
            if (DateTime.Today.AddDays(1) < date) throw new Exception("不支持查询未来日期");
            ComprehensiveInformationMonitoringModel model = new ComprehensiveInformationMonitoringModel() { 
                yestodayOperatingCapacity = 0,
                equipmentDowntimeCapacity = 0,
                //inputInstalledCapacity = await DataCache.InstallData.DayValue(DateTime.Now),
                //powerTotleValue = await DataCache.ActivePower.YearValue(DateTime.Now),
                inputInstalledCapacity = await InstallData(0),
                powerTotleValue = await AllActivePower(date),
                todayElectricityGenerationValue = await DataCache.PowerData.DayValue(date),
                plannedMaintenanceCapacity = 0
            };
            var powerLst = await this._db.tPowerStation.Where(x => x.dataState == 0).ToListAsync();
            model.Lst = new List<productionAndOperationInformation>();
            DateTime dateTime = new DateTime(date.Year,date.Month,date.Day);
            decimal yestodayAll = 0;
            for (int i = 0; i < powerLst.Count(); i++)
            {
                tPowerStation ps = powerLst[i];
                productionAndOperationInformation m = new productionAndOperationInformation()
                {
                    No = i + 1,
                    powerStationName = ps.powerStationName,
                    dayPowerValue = (await DataCache.PowerData.DayValue(date, ps.powerStationId)),
                    daySalePowerValue = (await DataCache.SalesData.DayValue(date, ps.powerStationId)),
                    monthPowerValue = (await DataCache.PowerData.MonthValue(date, ps.powerStationId)),
                    yearPowerValue = (await DataCache.PowerData.YearValue(date, ps.powerStationId)),
                    //inputInstalledCapacity = (await DataCache.planInstallDataYear.YearValue(date, ps.powerStationId)),
                    inputInstalledCapacity = await InstallData(ps.powerStationId),
                    yesterdayOperatingCapacity = (await DataCache.RunPower.DayValue(date.AddDays(-1), ps.powerStationId)),
                    totalInstalledUnits = await this._db.tPowerStationDevice.Where(x => x.devicePowerStation_powerStationId_fk == ps.powerStationId && x.deviceType_keyId_fk == 820094).CountAsync(),
                    numberOfOperatingUnits = await this._deviceDB.tStatisticsData.Where(x=>x.statisticsStation_powerStationId_fk == ps.powerStationId && x.statisticsDataDate >= dateTime && x.statisticsDataDate < dateTime.AddDays(1) && x.power > 0).GroupBy(x=>x.deviceGroup).CountAsync()
                    /*numberOfOperatingUnits = await this._deviceDB.tStatisticsData.Where(x=>x.statisticsStation_powerStationId_fk == ps.powerStationId
                                                                                           && x.statisticsDataDate > date.AddMinutes(-30)
                                                                                           && x.power > 0)
                                                                                 .Select(x=>x.deviceGroup)
                                                                                 .Distinct()
                                                                                 .CountAsync()*/
                };
                model.Lst.Add(m);
                yestodayAll += m.yesterdayOperatingCapacity;
            }
            model.yestodayOperatingCapacity = yestodayAll;
            return ResultApi.ok<ComprehensiveInformationMonitoringModel>(model);
        }


        /// <summary>
        /// 中心门户-生产全景
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<ProductionPanoramaModel>> ProductionPanorama()
        {
            ProductionPanoramaModel model = new ProductionPanoramaModel();

            //指标列表
            {
                model.indicatorList = new List<RequestStatisticsModel>();
                model.indicatorList.Add(new RequestStatisticsModel() { title = "投入装机容量", value = await InstallData(0) });
                model.indicatorList.Add(new RequestStatisticsModel() { title = "投入电站数量", value = await this._db.tPowerStation.Where(x => x.dataState == 0).CountAsync() });
                model.indicatorList.Add(new RequestStatisticsModel() { title = "昨日运行容量", value =  await DataCache.RunPower.DayValue(DateTime.Today.AddDays(-1))});
                model.indicatorList.Add(new RequestStatisticsModel() { title = "昨日发电量", value = await DataCache.PowerData.DayValue(DateTime.Today.AddDays(-1)) });
                model.indicatorList.Add(new RequestStatisticsModel() { title = "本月累计发电量", value = await DataCache.PowerData.MonthValue(DateTime.Today) });
                model.indicatorList.Add(new RequestStatisticsModel() { title = "本年累计发电量", value = await DataCache.PowerData.YearValue(DateTime.Today) });
                model.indicatorList.Add(new RequestStatisticsModel() { title = "昨日上网电量", value = await DataCache.SalesData.DayValue(DateTime.Today.AddDays(-1)) });
                model.indicatorList.Add(new RequestStatisticsModel() { title = "本月累计上网电量", value = await DataCache.SalesData.MonthValue(DateTime.Today) });
                model.indicatorList.Add(new RequestStatisticsModel() { title = "本年累计上网电量", value = await DataCache.SalesData.YearValue(DateTime.Today) });
                model.indicatorList.Add(new RequestStatisticsModel() { title = "昨日综合厂用电量", value = await DataCache.FactoryUsePower.DayValue(DateTime.Today.AddDays(-1))});
                model.indicatorList.Add(new RequestStatisticsModel() { title = "本月累计综合厂用电量", value = await DataCache.FactoryUsePower.MonthValue(DateTime.Today) });
                model.indicatorList.Add(new RequestStatisticsModel() { title = "本年累计综合厂用电量", value = await DataCache.FactoryUsePower.YearValue(DateTime.Today) });

            }
            //本月日发电量及去年同比
            {
                model.dailyPowerGenerationOfThisMonthAndYearOnYear = new List<RequestStatisticsModel>();
                for (DateTime i = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 01); i.IsSameMonth(DateTime.Now); i = i.AddDays(1))
                {
                    DateTime beforeDate = i.AddYears(-1);
                    model.dailyPowerGenerationOfThisMonthAndYearOnYear.Add(new RequestStatisticsModel()
                    {
                        title = $"{i:yyyy}年_{i:dd}",
                        value = await DataCache.PowerData.DayValue(i)
                    });
                    model.dailyPowerGenerationOfThisMonthAndYearOnYear.Add(new RequestStatisticsModel()
                    {
                        title = $"{beforeDate:yyyy}年_{beforeDate:dd}",
                        value = await DataCache.PowerData.DayValue(beforeDate)
                    });
                }
            }

            //区域公司昨日发电量占比
            {
                var areaLst = await this._db.tKey.Where(x => x.keyType == 5 && x.dataState == 0).FromCacheAsync();
                var totleValue = await DataCache.PowerData.DayValue(DateTime.Today.AddDays(-1));
                model.proportionOfPowerGenerationOfRegionalCompaniesYesterday = new List<RequestStatisticsModel>();
                foreach (var item in areaLst)
                {
                    model.proportionOfPowerGenerationOfRegionalCompaniesYesterday.Add(new RequestStatisticsModel
                    {
                        title = item.keyName,
                        value = totleValue > 0?((await DataCache.PowerData.DayValue(DateTime.Today.AddDays(-1),0,item.keyId)) / totleValue * 100):0
                    });
                }
            }

            //本月区域公司日发电量
            {
                var areaLst = await this._db.tKey.Where(x => x.keyType == 5 && x.dataState == 0).FromCacheAsync();
                model.dailyPowerGenerationOfRegionalCompaniesInThisMonth = new List<RequestStatisticsModel>();
                for (DateTime i = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 01); i.IsSameMonth(DateTime.Now); i = i.AddDays(1))
                {
                    foreach (var item in areaLst)
                    {
                        model.dailyPowerGenerationOfRegionalCompaniesInThisMonth.Add(new RequestStatisticsModel
                        {
                            title = $"{item.keyName}_{i:dd}",
                            value = await DataCache.PowerData.DayValue(i, 0, item.keyId)
                        });
                    }
                }
            }
            //区域公司本月发电量占比
            {
                var areaLst = await this._db.tKey.Where(x => x.keyType == 5 && x.dataState == 0).FromCacheAsync();
                var totleValue = await DataCache.PowerData.MonthValue(DateTime.Today);
                model.proportionOfPowerGenerationOfRegionalCompaniesInThisMonth = new List<RequestStatisticsModel>();
                foreach (var item in areaLst)
                {
                    model.proportionOfPowerGenerationOfRegionalCompaniesInThisMonth.Add(new RequestStatisticsModel
                    {
                        title = $"{item.keyName}",
                        value = totleValue > 0 ? (await DataCache.PowerData.MonthValue(DateTime.Today,0,item.keyId)) / totleValue * 100 : 0
                    });
                }
            }
            //昨日运行容量
            {
                var areaLst = await this._db.tKey.Where(x => x.keyType == 5 && x.dataState == 0).FromCacheAsync();
                model.yesterdayOperatingCapacity = new List<RequestStatisticsModel>();
                foreach (var item in areaLst)
                {
                    model.yesterdayOperatingCapacity.Add(new RequestStatisticsModel
                    {
                        title = $"{item.keyName}",
                        value = await DataCache.RunPower.DayValue(DateTime.Today.AddDays(-1),0,item.keyId),
                    });
                }
            }
            //装机容量占比
            {
                var areaLst = await this._db.tKey.Where(x => x.keyType == 5 && x.dataState == 0).FromCacheAsync();
                var totleValue = await InstallData(0);
                model.proportionOfInstalledCapacity = new List<RequestStatisticsModel>();
                foreach (var item in areaLst)
                {
                    model.proportionOfInstalledCapacity.Add(new RequestStatisticsModel
                    {
                        title = $"{item.keyName}",
                        value =totleValue == 0?0: (await DataCache.InstallData.DayValue(DateTime.Today,0,item.keyId) / totleValue * 100)
                    });
                }
            }

            return ResultApi.ok<ProductionPanoramaModel>(model);
        }



        /// <summary>
        /// 中心门户-中心门户-总部门户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<CentralPortalBase>> HeadquartersPortalList()
        {
            DateTime threaYear = new DateTime(DateTime.Today.Year - 3, 1, 1);
            //电站列表
            var stationLst = await this._db.vPowerStation.Where(x => x.dataState == 0).ToListAsync();
            CentralPortalBase model = new CentralPortalBase();
            //总发电量,电站数量,总装机容量,总有功功率
            {
                model.totalPowerGeneration = new List<RequestStatisticsModel>();
                model.totalPowerGeneration.Add(new RequestStatisticsModel { title= "本年" ,value = await DataCache.PowerData.YearValue(DateTime.Today)});
                model.totalPowerGeneration.Add(new RequestStatisticsModel { title = "本月", value = await DataCache.PowerData.MonthValue(DateTime.Today) });
                model.totalPowerGeneration.Add(new RequestStatisticsModel { title = "昨日", value = await DataCache.PowerData.DayValue(DateTime.Today.AddDays(-1)) });
                model.totalPowerGeneration.Add(new RequestStatisticsModel { title = "电站数量", value = await this._db.tPowerStation.Where(x => x.dataState == 0).CountAsync() });
                // TODO:总装机容量
                model.totalPowerGeneration.Add(new RequestStatisticsModel { title = "总装机容量", value = (await InstallData(0)) });
                model.totalPowerGeneration.Add(new RequestStatisticsModel { title = "总有功功率", value = (await AllActivePower(new DateTime(1900,1,1))) });
            }
            //发电概览
            {
                model.powerGenerationOverview = new List<RequestStatisticsModel>();
                model.powerGenerationOverview.Add(new RequestStatisticsModel { title = "年计划", value = await DataCache.PlanDataOfYear.YearValue(DateTime.Today) });
                model.powerGenerationOverview.Add(new RequestStatisticsModel { title = "已完成", value = await DataCache.PowerData.YearValue(DateTime.Today) });
                // TODO:总装机容量,总有功功率
                model.powerGenerationOverview.Add(new RequestStatisticsModel { title = "总装机容量",value = await InstallData(0) });
                model.powerGenerationOverview.Add(new RequestStatisticsModel { title = "总有功功率", value = await AllActivePower(new DateTime(1900,1,1)) });
            }
            //计划发电完成情况
            { 
                model.completionOfPlannedPowerGeneration = new List<RequestStatisticsModel>();
                for (DateTime i = new DateTime(DateTime.Today.Year,1,1); i.IsSameYear(DateTime.Today); i = i.AddMonths(1))
                {
                    DateTime i1 = i.AddYears(-1);
                    DateTime i2 = i1.AddYears(-1);
                    model.completionOfPlannedPowerGeneration.Add(new RequestStatisticsModel { title = $"{i:yyyy}年_{i:MM}月", value = await DataCache.PowerData.MonthValue(i) });
                    model.completionOfPlannedPowerGeneration.Add(new RequestStatisticsModel { title = $"{i1:yyyy}年_{i1:MM}月", value = await DataCache.PowerData.MonthValue(i1) });
                    model.completionOfPlannedPowerGeneration.Add(new RequestStatisticsModel { title = $"{i2:yyyy}年_{i2:MM}月", value = await DataCache.PowerData.MonthValue(i2) });
                }
            }
            //电站发电排名情况
            {
                model.powerGenerationRanking = new List<RequestStatisticsModel>();
                foreach (var item in stationLst)
                {
                    model.powerGenerationRanking.Add(new RequestStatisticsModel { 
                        title = item.powerStationName+"_已完成发电",
                        value = await DataCache.PowerData.MonthValue(DateTime.Today,item.powerStationId)
                    });
                    model.powerGenerationRanking.Add(new RequestStatisticsModel
                    {
                        title = item.powerStationName+"_计划发电",
                        value = await DataCache.PlanDataOfYear.YearValue(DateTime.Today,item.powerStationId)
                    });
                    model.powerGenerationRanking.Add(new RequestStatisticsModel
                    {
                        title = item.powerStationName + "_今日发电量",
                        value = await DataCache.PowerData.DayValue(DateTime.Today, item.powerStationId)
                    });
                    model.powerGenerationRanking.Add(new RequestStatisticsModel
                    {
                        title = item.powerStationName + "_今日上网电量",
                        value = await DataCache.SalesData.DayValue(DateTime.Today, item.powerStationId)
                    });
                    model.powerGenerationRanking.Add(new RequestStatisticsModel
                    {
                        title = item.powerStationName + "_今日厂用电量",
                        value = await DataCache.FactoryUsePower.DayValue(DateTime.Today, item.powerStationId)
                    });
                }
            }
            //近三年上网电量对比
            {
                model.comparisonOfOnGridPowerInRecentThreeYears = new List<RequestStatisticsModel>();
                for (DateTime i = new DateTime(DateTime.Today.Year, 1, 1); i.IsSameYear(DateTime.Today); i = i.AddMonths(1))
                {
                    DateTime i1 = i.AddYears(-1);
                    DateTime i2 = i1.AddYears(-1);
                    model.comparisonOfOnGridPowerInRecentThreeYears.Add(new RequestStatisticsModel { title = $"{i:yyyy}年_{i:MM}月", value = await DataCache.SalesData.MonthValue(i) });
                    model.comparisonOfOnGridPowerInRecentThreeYears.Add(new RequestStatisticsModel { title = $"{i1:yyyy}年_{i1:MM}月", value = await DataCache.SalesData.MonthValue(i1) });
                    model.comparisonOfOnGridPowerInRecentThreeYears.Add(new RequestStatisticsModel { title = $"{i2:yyyy}年_{i2:MM}月", value = await DataCache.SalesData.MonthValue(i2) });
                }
            }
            model.powerStations = stationLst;
            return ResultApi.ok<CentralPortalBase>(model, 0);
        }

        /// <summary>
        /// 中心门户-中心门户-区域门户
        /// </summary>
        /// <param name="keyId">区域ID,如果不传将返回默认的第一个</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<CentralPortalArea>> HeadquartersPortalAreaList(long? keyId)
        {
            CentralPortalArea model = new CentralPortalArea();
            model.areaLst = await this._db.tKey.Join(this._db.tPowerStation.Where(x => x.dataState == 0), x=>x.keyId,k=>k.powerStationArea_keyId_fk,(x,k)=>x).ToListAsync();
            if(keyId.HasValue == false)
            {
                keyId = model.areaLst.First().keyId;
            }
            DateTime threaYear = new DateTime(DateTime.Today.Year - 3, 1, 1);
            //电站列表
            var stationLst = await this._db.vPowerStation.Where(x => x.dataState == 0 && x.powerStationArea_keyId_fk == keyId).ToListAsync();
            if (!stationLst.Any()) return ResultApi.error<CentralPortalArea>(null,"该区域无电站");

            //总发电量,电站数量,总装机容量,总有功功率
            {
                model.totalPowerGeneration = new List<RequestStatisticsModel>();
                model.totalPowerGeneration.Add(new RequestStatisticsModel { title = "本年", value = await DataCache.PowerData.YearValue(DateTime.Today, 0, keyId ?? 0) });
                model.totalPowerGeneration.Add(new RequestStatisticsModel { title = "本月", value = await DataCache.PowerData.MonthValue(DateTime.Today, 0, keyId ?? 0) });
                model.totalPowerGeneration.Add(new RequestStatisticsModel { title = "昨日", value = await DataCache.PowerData.YearValue(DateTime.Today.AddDays(-1), 0, keyId ?? 0) });
                model.totalPowerGeneration.Add(new RequestStatisticsModel { title = "电站数量", value = await this._db.tPowerStation.Where(x => x.dataState == 0 && x.powerStationArea_keyId_fk == keyId).CountAsync() });
                // TODO:总装机容量
                model.totalPowerGeneration.Add(new RequestStatisticsModel { title = "总装机容量", value = (await InstallData(0)) });
                model.totalPowerGeneration.Add(new RequestStatisticsModel { title = "总有功功率", value = (await AllActivePower(new DateTime(1900,1,1))) });
            }
            //发电概览
            {
                model.powerGenerationOverview = new List<RequestStatisticsModel>();
                model.powerGenerationOverview.Add(new RequestStatisticsModel { title = "年计划", value = await DataCache.planInstallDataYear.YearValue(DateTime.Today,0,keyId??0) });
                model.powerGenerationOverview.Add(new RequestStatisticsModel { title = "已完成", value = await DataCache.PowerData.YearValue(DateTime.Today, 0, keyId ?? 0) });
                // TODO:总装机容量,总有功功率
                model.powerGenerationOverview.Add(new RequestStatisticsModel { title = "总装机容量", value = await InstallData(0) });
                model.powerGenerationOverview.Add(new RequestStatisticsModel { title = "总有功功率", value = await AllActivePower(new DateTime(1900,1,1)) });
            }
            //计划发电完成情况
            {
                model.completionOfPlannedPowerGeneration = new List<RequestStatisticsModel>();
                for (DateTime i = new DateTime(DateTime.Today.Year, 1, 1); i.IsSameYear(DateTime.Today); i = i.AddMonths(1))
                {
                    DateTime i1 = i.AddYears(-1);
                    DateTime i2 = i1.AddYears(-1);
                    model.completionOfPlannedPowerGeneration.Add(new RequestStatisticsModel { title = $"{i:yyyy}年_{i:MM}月", value = await DataCache.PowerData.MonthValue(i,0,keyId??0) });
                    model.completionOfPlannedPowerGeneration.Add(new RequestStatisticsModel { title = $"{i1:yyyy}年_{i1:MM}月", value = await DataCache.PowerData.MonthValue(i1, 0, keyId ?? 0) });
                    model.completionOfPlannedPowerGeneration.Add(new RequestStatisticsModel { title = $"{i2:yyyy}年_{i2:MM}月", value = await DataCache.PowerData.MonthValue(i2, 0, keyId ?? 0) });
                }
            }
            //电站发电排名情况
            {
                model.powerGenerationRanking = new List<RequestStatisticsModel>();
                foreach (var item in stationLst)
                {
                    model.powerGenerationRanking.Add(new RequestStatisticsModel
                    {
                        title = item.powerStationName + "_已完成发电",
                        value = await DataCache.PowerData.YearValue(DateTime.Today, item.powerStationId)
                    });
                    model.powerGenerationRanking.Add(new RequestStatisticsModel
                    {
                        title = item.powerStationName + "_计划发电",
                        value = await DataCache.planInstallDataYear.YearValue(DateTime.Today,item.powerStationId)
                    });
                    model.powerGenerationRanking.Add(new RequestStatisticsModel
                    {
                        title = item.powerStationName + "_今日发电量",
                        value = await DataCache.PowerData.DayValue(DateTime.Today, item.powerStationId)
                    });
                    model.powerGenerationRanking.Add(new RequestStatisticsModel
                    {
                        title = item.powerStationName + "_今日上网电量",
                        value = await DataCache.SalesData.YearValue(DateTime.Today, item.powerStationId)
                    });
                    model.powerGenerationRanking.Add(new RequestStatisticsModel
                    {
                        title = item.powerStationName + "_今日厂用电量",
                        value = model.powerGenerationRanking.First(x => x.title == item.powerStationName + "_今日发电量").value - model.powerGenerationRanking.First(x => x.title == item.powerStationName + "_今日上网电量").value
                    });

                }
            }
            //近三年上网电量对比
            {
                model.comparisonOfOnGridPowerInRecentThreeYears = new List<RequestStatisticsModel>();
                for (DateTime i = new DateTime(DateTime.Today.Year, 1, 1); i.IsSameYear(DateTime.Today); i = i.AddMonths(1))
                {
                    DateTime i1 = i.AddYears(-1);
                    DateTime i2 = i1.AddYears(-1);
                    model.comparisonOfOnGridPowerInRecentThreeYears.Add(new RequestStatisticsModel { title = $"{i:yyyy}年_{i:MM}月", value = await DataCache.SalesData.MonthValue(i,0,keyId??0) });
                    model.comparisonOfOnGridPowerInRecentThreeYears.Add(new RequestStatisticsModel { title = $"{i1:yyyy}年_{i1:MM}月", value = await DataCache.SalesData.MonthValue(i1, 0, keyId ?? 0) });
                    model.comparisonOfOnGridPowerInRecentThreeYears.Add(new RequestStatisticsModel { title = $"{i2:yyyy}年_{i2:MM}月", value = await DataCache.SalesData.MonthValue(i2, 0, keyId ?? 0) });
                }
            }
            model.powerStations = stationLst;
            return ResultApi.ok<CentralPortalArea>(model, 0);
        }


        /// <summary>
        /// 中心门户-中心门户-单电站门户
        /// </summary>
        /// <param name="powerStationId">电站ID,如果不传将返回默认的第一个</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<CentralPortalArea>> HeadquartersPortalPowerStationList(long? powerStationId)
        {
            CentralPortalArea model = new CentralPortalArea();
            //电站列表
            var stationLst = await this._db.vPowerStation.Join(this._db.tUserPowerStation.Where(x=>x.ups_user_userId_fk == this.userId),x=>x.powerStationId,k=>k.ups_powerStation_powerStationId_fk,(x,k)=>x).Where(x => x.dataState == 0).ToListAsync();
            if (!stationLst.Any()) return ResultApi.error<CentralPortalArea>(null, "未绑定有电站");
            var stationIdLst = stationLst.Select(x=>x.powerStationArea_keyId_fk);
            model.areaLst = await this._db.tKey.Where(x=>stationIdLst.Any(k=>k == x.keyId)).ToListAsync();
            if (powerStationId.HasValue == false)
            {
                powerStationId = stationLst.First().powerStationId;
            }
            DateTime threaYear = new DateTime(DateTime.Today.Year - 3, 1, 1);
            

            //总发电量,电站数量,总装机容量,总有功功率
            {
                model.totalPowerGeneration = new List<RequestStatisticsModel>();
                model.totalPowerGeneration.Add(new RequestStatisticsModel { title = "本年", value = await DataCache.PowerData.YearValue(DateTime.Today,powerStationId??0) });
                model.totalPowerGeneration.Add(new RequestStatisticsModel { title = "本月", value = await DataCache.PowerData.MonthValue(DateTime.Today, powerStationId ?? 0) });
                model.totalPowerGeneration.Add(new RequestStatisticsModel { title = "昨日", value = await DataCache.PowerData.DayValue(DateTime.Today.AddDays(-1), powerStationId ?? 0) });
                model.totalPowerGeneration.Add(new RequestStatisticsModel { title = "电站数量", value = 1 });//await this._db.tPowerStation.Where(x => x.dataState == 0).CountAsync() });
                // TODO:总装机容量
                model.totalPowerGeneration.Add(new RequestStatisticsModel { title = "总装机容量", value = await InstallData((long)powerStationId) });
                model.totalPowerGeneration.Add(new RequestStatisticsModel { title = "总有功功率", value = await AllActivePower(new DateTime(1900,1,1)) });

            }
            //发电概览
            {
                model.powerGenerationOverview = new List<RequestStatisticsModel>();
                model.powerGenerationOverview.Add(new RequestStatisticsModel { title = "年计划", value = await DataCache.planInstallDataYear.YearValue(DateTime.Today,powerStationId??0) });
                model.powerGenerationOverview.Add(new RequestStatisticsModel { title = "已完成", value = await DataCache.PowerData.YearValue(DateTime.Today,powerStationId??0) });
                // TODO:总装机容量,总有功功率
                model.powerGenerationOverview.Add(new RequestStatisticsModel { title = "总装机容量", value = await InstallData((long)powerStationId) });
                model.powerGenerationOverview.Add(new RequestStatisticsModel { title = "总有功功率", value = await AllActivePower(new DateTime(1900,1,1))  });
            }
            //计划发电完成情况
            {
                model.completionOfPlannedPowerGeneration = new List<RequestStatisticsModel>();
                for (DateTime i = new DateTime(DateTime.Today.Year, 1, 1); i.IsSameYear(DateTime.Today); i = i.AddMonths(1))
                {
                    DateTime i1 = i.AddYears(-1);
                    DateTime i2 = i1.AddYears(-1);
                    model.completionOfPlannedPowerGeneration.Add(new RequestStatisticsModel { title = $"{i:yyyy}年_{i:MM}月", value = await DataCache.PowerData.MonthValue(i,powerStationId??0) });
                    model.completionOfPlannedPowerGeneration.Add(new RequestStatisticsModel { title = $"{i1:yyyy}年_{i1:MM}月", value = await DataCache.PowerData.MonthValue(i1, powerStationId ?? 0) });
                    model.completionOfPlannedPowerGeneration.Add(new RequestStatisticsModel { title = $"{i2:yyyy}年_{i2:MM}月", value = await DataCache.PowerData.MonthValue(i2, powerStationId ?? 0) });
                }
            }
            //电站发电排名情况
            {
                model.powerGenerationRanking = new List<RequestStatisticsModel>();
                foreach (var item in stationLst)
                {
                    model.powerGenerationRanking.Add(new RequestStatisticsModel
                    {
                        title = item.powerStationName + "_已完成发电",
                        value = await DataCache.PowerData.YearValue(DateTime.Today, item.powerStationId)
                    });
                    model.powerGenerationRanking.Add(new RequestStatisticsModel
                    {
                        title = item.powerStationName + "_计划发电",
                        value = await DataCache.planInstallDataYear.YearValue(DateTime.Today, item.powerStationId)
                    });
                    model.powerGenerationRanking.Add(new RequestStatisticsModel
                    {
                        title = item.powerStationName + "_今日发电量",
                        value = await DataCache.PowerData.DayValue(DateTime.Today, item.powerStationId)
                    });
                    model.powerGenerationRanking.Add(new RequestStatisticsModel
                    {
                        title = item.powerStationName + "_今日上网电量",
                        value = await DataCache.SalesData.YearValue(DateTime.Today, item.powerStationId)
                    });
                    model.powerGenerationRanking.Add(new RequestStatisticsModel
                    {
                        title = item.powerStationName + "_今日厂用电量",
                        value = model.powerGenerationRanking.First(x=>x.title == item.powerStationName + "_今日发电量").value - model.powerGenerationRanking.First(x => x.title == item.powerStationName + "_今日上网电量").value
                    });

                }
            }
            //近三年上网电量对比
            {
                model.comparisonOfOnGridPowerInRecentThreeYears = new List<RequestStatisticsModel>();
                for (DateTime i = new DateTime(DateTime.Today.Year, 1, 1); i.IsSameYear(DateTime.Today); i = i.AddMonths(1))
                {
                    DateTime i1 = i.AddYears(-1);
                    DateTime i2 = i1.AddYears(-1);
                    model.comparisonOfOnGridPowerInRecentThreeYears.Add(new RequestStatisticsModel { title = $"{i:yyyy}年_{i:MM}月", value = await DataCache.SalesData.MonthValue(i, powerStationId ?? 0) });
                    model.comparisonOfOnGridPowerInRecentThreeYears.Add(new RequestStatisticsModel { title = $"{i1:yyyy}年_{i1:MM}月", value = await DataCache.SalesData.MonthValue(i1, powerStationId ?? 0) });
                    model.comparisonOfOnGridPowerInRecentThreeYears.Add(new RequestStatisticsModel { title = $"{i2:yyyy}年_{i2:MM}月", value = await DataCache.SalesData.MonthValue(i2, powerStationId ?? 0) });
                }
            }
            model.powerStations = stationLst;
            return ResultApi.ok<CentralPortalArea>(model, 0);
        }


        /// <summary>
        /// 单电站管理-首页
        /// </summary>
        /// <param name="powerStationId">电站ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<singlePowerStationManagementIndex>> SinglePowerStationManagementIndex(long powerStationId)
        {
            singlePowerStationManagementIndex m = new singlePowerStationManagementIndex();
            //昨日发电量,今日发电量,年计划发电量,年发电量,容量利用占比装机容量,电站发电占比电站发电
            {
                m.BaseData = new List<RequestStatisticsModel>();
                m.BaseData.Add(new RequestStatisticsModel { title= "昨日发电量",value = await DataCache.PowerData.DayValue(DateTime.Today.AddDays(-1), powerStationId) });
                m.BaseData.Add(new RequestStatisticsModel { title = "今日发电量", value = await DataCache.PowerData.DayValue(DateTime.Today, powerStationId) });
                m.BaseData.Add(new RequestStatisticsModel { title = "年计划", value = await DataCache.PlanDataOfYear.YearValue(DateTime.Today, powerStationId) });
                m.BaseData.Add(new RequestStatisticsModel { title = "已完成", value = await PowerData(powerStationId,DateTime.Today.Year) });
                m.BaseData.Add(new RequestStatisticsModel { title = "装机容量", value = await InstallData(powerStationId) });
                m.BaseData.Add(new RequestStatisticsModel { title = "集团装机容量", value = await InstallData(0) });
                //m.BaseData.Add(new RequestStatisticsModel { title = "发电量", value = await DataCache.PowerData.YearValue(DateTime.Today, powerStationId) });
                m.BaseData.Add(new RequestStatisticsModel { title = "发电量", value = await PowerData(powerStationId,DateTime.Now.Year) });
                m.BaseData.Add(new RequestStatisticsModel { title = "集团发电量", value = await PowerData(0,DateTime.Today.Year) });
            }

            var deviceLst = await this._db.tPowerStationDevice.Where(x => x.dataState == 0 && x.devicePowerStation_powerStationId_fk == powerStationId && x.deviceType_keyId_fk == 820094).OrderByDescending(x=>x.deviceGroup).ToListAsync();
            //电站月度降雨量/发电量对比
            {
                m.twoYearPowerValue = new List<RequestStatisticsModel>();
                m.twoYearRainfallValue = new List<RequestStatisticsModel>();
                m.twoYearPowerTimeValue = new List<RequestStatisticsModel>();
                for (DateTime i = new DateTime(DateTime.Today.Year - 1,1,1); i.Year <= DateTime.Today.Year; i = i.AddMonths(1))
                {
                    /*m.twoYearPowerValue.Add(new RequestStatisticsModel {title=$"{i:yyyy}发电_{i:MM}月" ,value = await DataCache.PowerData.MonthValue(i, powerStationId) });
                    m.twoYearRainfallValue.Add(new RequestStatisticsModel { title = $"{i:yyyy}降雨_{i:MM}月", value = await DataCache.RainfallData.MonthValue(i, powerStationId) });
                    foreach (var device in deviceLst)
                    {
                        m.twoYearPowerTimeValue.Add(new RequestStatisticsModel { title = $"{device.deviceName}_{i:yyyy}年_{i:MM}月", value = (await DataCache.PowerTimeData.MonthValue(i, 0,0,device.deviceGroup))/(((i.AddMonths(1) - i)).TotalHours).ConvertTo<decimal>()});
                    }*/
                    m.twoYearPowerValue.Add(new RequestStatisticsModel { title = $"{i:yyyy}发电_{i:MM}月", value = await ValueOfTwoYear(i,powerStationId, "twoYearPowerValue",null) });
                    m.twoYearRainfallValue.Add(new RequestStatisticsModel { title = $"{i:yyyy}降雨_{i:MM}月", value = await ValueOfTwoYear(i, powerStationId, "twoYearRainfallValue",null) });
                    foreach (var device in deviceLst)
                    {
                        m.twoYearPowerTimeValue.Add(new RequestStatisticsModel { title = $"{device.deviceName}_{i:yyyy}年_{i:MM}月", value = (await ValueOfTwoYear(i, powerStationId, "twoYearPowerTimeValue",device)) / (((i.AddMonths(1) - i)).TotalHours).ConvertTo<decimal>() });
                    }
                }
            }
            ///机组数据
            {
                m.generatorSetDataLst = new List<GeneratorSetData>();
                foreach (var device in deviceLst)
                {
                    m.generatorSetDataLst.Add(new GeneratorSetData
                    {
                        Name = device.deviceName,
                        DeviceType = await deviceTypeGet(device),
                        beforeYearPowerValue = await PowerData(powerStationId, DateTime.Today.AddYears(-1).Year, device.deviceGroup),
                        InstalledCapacity = await DataCache.InstallData.YearValue(DateTime.Today, device.devicePowerStation_powerStationId_fk, 0, device.deviceGroup),
                        normalOperation = await DownTimeForYear(await DataCache.PowerTimeData.YearValue(DateTime.Today, device.devicePowerStation_powerStationId_fk, 0, device.deviceGroup), "normalOperation"),
                        thisDowntime = await thisDownTime(device),
                        thisShutdownLasts = Math.Round((await thisDownTime(device)) / 24, 0),
                        todayPowerValue = await DataCache.PowerData.DayValue(DateTime.Today, device.devicePowerStation_powerStationId_fk, 0, device.deviceGroup),
                        yearDurationOfPowerFailure = await DownTimeForYear(await DataCache.PowerTimeData.YearValue(DateTime.Today, device.devicePowerStation_powerStationId_fk, 0, device.deviceGroup), "yearDurationOfPowerFailure"),
                        yearGenerationDuration = await DataCache.PowerTimeData.YearValue(DateTime.Today, device.devicePowerStation_powerStationId_fk, 0, device.deviceGroup),
                        yestodayPowerValue = await DataCache.PowerData.DayValue(DateTime.Today.AddDays(-1), device.devicePowerStation_powerStationId_fk, 0, device.deviceGroup),
                        yearPowrValue = await PowerData(powerStationId, DateTime.Today.Year, device.deviceGroup),
                        yearPeacetimePowerValue = await DataCache.PowerFlatData.YearValue(DateTime.Today, device.devicePowerStation_powerStationId_fk, 0, device.deviceGroup),
                        yearPeakPowerValue = await DataCache.PowerPeakData.YearValue(DateTime.Today, device.devicePowerStation_powerStationId_fk, 0, device.deviceGroup),
                        yearValleyPower = await DataCache.PowerValleyData.YearValue(DateTime.Today, device.devicePowerStation_powerStationId_fk, 0, device.deviceGroup)
                    }) ;
                }
            }

            return ResultApi.ok<singlePowerStationManagementIndex>(m);
        }

        private Task<decimal> DownTimeForYear(decimal v,string type)
        {
            Task<decimal> task = null;
            if (type == "normalOperation")
            {
                task = Task.Run(() =>
                {
                    TimeSpan timeSpan = DateTime.Now - new DateTime(DateTime.Now.Year, 1, 1);
                    decimal cha = Math.Round( v / new decimal(timeSpan.TotalHours) * 100, 2);
                    return cha;
                });
            }
            if (type == "yearDurationOfPowerFailure")
            {
                task = Task.Run(() =>
                {
                    TimeSpan timeSpan = DateTime.Now - new DateTime(DateTime.Now.Year, 1, 1);
                    decimal cha = Math.Round(new decimal(timeSpan.TotalHours) - v, 0);
                    return cha;
                });
            }
            return task;
        }

        private async Task<decimal> thisDownTime(tPowerStationDevice device)
        {
            decimal year = DateTime.Now.Year;
            string yearStart = year + "-01-01 00:00:00";
            DateTime startTime = Convert.ToDateTime(yearStart);
            //查最后一条发电时长统计不为零的当做关机时间
            var start = await this._deviceDB.tStatisticsData.OrderByDescending(x => x.statisticsDataDate).FirstOrDefaultAsync(x => x.statisticsStation_powerStationId_fk == device.devicePowerStation_powerStationId_fk && x.powerGenerationTime != 0 && x.deviceGroup == device.deviceGroup && x.statisticsDataDate >= startTime);
            //查最后一条发电时长统计为零的当做开机时间
            var end = await this._deviceDB.tStatisticsData.OrderByDescending(x => x.statisticsDataDate).FirstOrDefaultAsync(x => x.statisticsStation_powerStationId_fk == device.devicePowerStation_powerStationId_fk && x.powerGenerationTime == 0 && x.deviceGroup == device.deviceGroup && x.statisticsDataDate >= startTime);
            if (start == null)
            {
                TimeSpan timeSpan = DateTime.Now - startTime;
                decimal timeH = Math.Round(new decimal(timeSpan.TotalHours), 0);
                return timeH;
            }
            if (end == null)
            {
                return 0;
            }
            if (start.statisticsDataDate > end.statisticsDataDate)
            {
                return 0;
            }
            else
            {
                TimeSpan timeSpan = DateTime.Now - start.statisticsDataDate;
                decimal timeH = Math.Round(new decimal(timeSpan.TotalHours), 2);
                return timeH;
            }
        }

        private async Task<string> deviceTypeGet(tPowerStationDevice device)
        {
            var type = await this._deviceDB.tStatisticsSingleData.FirstOrDefaultAsync(data =>  data.deviceGroup == device.deviceGroup && data.powerStation_SingleData_powerStationId_fk == device.devicePowerStation_powerStationId_fk);
            if (type == null)
            {
                return "冲击式";
            }
            return type.deviceType;
        }

        private async Task<decimal> PowerData(long powerStationId ,int year,String deviceGroup = "")
        {
            IQueryable<vStatisticsData> datalist;
            if (powerStationId != 0)
            {
                
                if ("".Equals(deviceGroup))
                {
                    datalist = this._deviceDB.vStatisticsData.Where(x =>
                        x.statisticsStation_powerStationId_fk == powerStationId && x.statisticsDataDate.Year == year);
                }
                else
                {
                    datalist = this._deviceDB.vStatisticsData.Where(x =>
                        x.statisticsStation_powerStationId_fk == powerStationId && x.statisticsDataDate.Year == year && deviceGroup.Equals(x.deviceGroup));
                }
            }
            else
            {
                datalist = this._deviceDB.vStatisticsData.Where(x =>
                    x.statisticsDataDate.Year == year);
            }

            if (datalist.Count() != 0)
            {
                decimal data = await datalist.SumAsync(x => x.power);
                return data;
            }
            else
            {
                return 0;
            }
            throw new NotImplementedException();
        }

        private async Task<decimal> ValueOfTwoYear(DateTime i, long powerStationId, string v, tPowerStationDevice devicev)
        {
            IQueryable<vStatisticsData> datalist = null;decimal data = 0;
            switch (v)
            {
                case "twoYearPowerValue":
                    //对powerdata进行月汇总
                    datalist = this._deviceDB.vStatisticsData.Where(x => x.statisticsStation_powerStationId_fk == powerStationId && x.statisticsDataDate >= i && x.statisticsDataDate < i.AddMonths(1));
                    if (datalist.Count() != 0)
                    {
                        data = await datalist.SumAsync(x => x.power);
                        return data;
                    }
                    return data;
                case "twoYearRainfallValue":
                    //对rainfalldata进行月汇总
                    datalist = this._deviceDB.vStatisticsData.Where(x => x.statisticsStation_powerStationId_fk == powerStationId && x.statisticsDataDate >= i && x.statisticsDataDate < (i.AddMonths(1)));
                    if (datalist.Count() != 0)
                    {
                        data = await datalist.SumAsync(x => x.rainfall);
                        return data;
                    }
                    return data;
                case "twoYearPowerTimeValue":
                    //对电站机组进行月汇总
                    datalist = this._deviceDB.vStatisticsData.Where(x => x.statisticsStation_powerStationId_fk == powerStationId && x.statisticsDataDate >= i && x.statisticsDataDate < i.AddMonths(1) && x.deviceGroup == devicev.deviceGroup);
                    if (datalist.Count() != 0)
                    {
                        data = await datalist.SumAsync(group=>group.powerGenerationTime)/3600;
                        return data;
                    }
                    return data;
                default:
                    break;
            }
            throw new NotImplementedException();
        }



        /// <summary>
        /// 移动端-实时运行数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<RequestStatisticsModel>>> PhoneData(int powerStationId,DateTime date)
        {
            var lst = new List<RequestStatisticsModel>();
            decimal gl = 0;
            var m = await this._db.tPowerStation.FirstOrDefaultAsync(x => x.powerStationId == powerStationId);
            var no = m.powerStationNo;

            //var keys = _redisUtil.Kyes($"/{no}/unit1/analog");
            /*var unit1 = await _redisUtil.GetStringKey<Dictionary<string,decimal>>($"/{no}/unit1/analog");
            var unit2 = await _redisUtil.GetStringKey<Dictionary<string, decimal>>($"/{no}/unit2/analog");
            var unit3 = await _redisUtil.GetStringKey<Dictionary<string, decimal>>($"/{no}/unit3/analog");*/

            List<string> unitAll = _redisUtil.Keys($"/{no}/*/analog").ToList();

            if (unitAll != null)
            {
                foreach (var item in unitAll)
                {
                    var keyValues = await _redisUtil.GetStringKey<Dictionary<string, decimal>>(item);
                    if (keyValues.ContainsKey($"analog31"))
                    {
                        gl += keyValues["analog31"];
                    }
                }
            }

            /*if (unit1!=null && unit1.ContainsKey($"analog31"))
            {
                gl += unit1["analog31"];
            }
            if (unit2 != null && unit2.ContainsKey($"analog31"))
            {
                gl += unit2["analog31"];
            }
            if (unit3 != null && unit3.ContainsKey($"analog31"))
            {
                gl += unit3["analog31"];
            }*/

            lst.Add(new RequestStatisticsModel { title = "实时功率", value = gl });
            lst.Add(new RequestStatisticsModel { title = "日发电量", value = await DataCache.PowerData.DayValue(date.Date,powerStationId) });
            lst.Add(new RequestStatisticsModel { title = "月发电量", value = await DataCache.PowerData.MonthValue(date.Date, powerStationId) });
            lst.Add(new RequestStatisticsModel { title = "年发电量", value = await DataCache.PowerData.YearValue(date.Date, powerStationId) });
            lst.Add(new RequestStatisticsModel { title = "日上网电量", value = await DataCache.SalesData.DayValue(date.Date, powerStationId) });
            lst.Add(new RequestStatisticsModel { title = "日厂用电量", value = await DataCache.FactoryUsePower.DayValue(date.Date,powerStationId) });
            return ResultApi.ok<List<RequestStatisticsModel>>(lst, 0);
        }

        /// <summary>
        /// 单电站管理-智能监控-机组功率测试表格数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<RequestStatisticsPowerModel>>> UnitPowerMonitoringModel(long powerStationId)
        {
            await this.IsCheckPowerStation(powerStationId);
            var m = await this._db.tPowerStation.FirstOrDefaultAsync(x => x.powerStationId == powerStationId);
            if (m == null) return ResultApi.okOrError<List<RequestStatisticsPowerModel>>(false,null);
            var model = new RequestStatisticsPowerModel() { 
                activePower = await DataCache.ActivePower.DayValue(DateTime.Now,powerStationId),
                reactivePower = await DataCache.ReactivePower.DayValue(DateTime.Now, powerStationId),
                date = DateTime.Now.Date,
                powerStationName = m.powerStationName,
                powerStationNo = m.powerStationNo
            };
            return ResultApi.okOrError<List<RequestStatisticsPowerModel>>(true,new List<RequestStatisticsPowerModel>() { model});
        }
        /// <summary>
        /// 单电站管理-智能监控-机组功率测试图表数据
        /// </summary>
        /// <param name="powerStationId">电站Id</param>
        /// <param name="type">1表示分机组返回,2表示整个电站累加</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultApi<List<RequestStatisticsModel>>> UnitPowerMonitoringList(long powerStationId,int type=1)
        {
            await this.IsCheckPowerStation(powerStationId);
            var startTime = DateTime.Now.AddDays(-1).Date;
            var deviceList = await this._db.tPowerStationDevice.Where(x => x.devicePowerStation_powerStationId_fk == powerStationId && x.deviceType_keyId_fk == 820094).ToListAsync();
            var lst = new List<RequestStatisticsModel>();
            for (DateTime i = startTime; i < DateTime.Now.AddDays(1).Date;i = i.AddDays(1))
            {
                if (type == 1)
                {
                    
                    foreach (var item in deviceList)
                    {
                        lst.Add(new RequestStatisticsModel { title = $"{item.deviceName}_{i:yyyy-MM-dd}_有功功率", value =await DataCache.ActivePower.DayValue(i,powerStationId,0,item.deviceGroup) });
                        lst.Add(new RequestStatisticsModel { title = $"{item.deviceName}_{i:yyyy-MM-dd}_无功功率", value = await DataCache.ReactivePower.DayValue(i, powerStationId, 0, item.deviceGroup) });
                    }
                }
                else {
                    lst.Add(new RequestStatisticsModel { title = $"{i:yyyy-MM-dd}_有功功率", value = await DataCache.ActivePower.DayValue(i, powerStationId) });
                    lst.Add(new RequestStatisticsModel { title = $"{i:yyyy-MM-dd}_无功功率", value = await DataCache.ReactivePower.DayValue(i, powerStationId) });
                }
            }

            return ResultApi.okOrError<List<RequestStatisticsModel>>(true,lst);
        }


        private async Task<decimal> AllActivePower(DateTime date)
        {
            //int yearNow = DateTime.Now.Year;
            //var beilvs = this._db.tPowerStation.Select(x => new BeilvDual { powerStationId = x.powerStationId, powerRate = x.powerRate }).ToList();
            IQueryable<vStatisticsData> avglist;
            if (!date.IsSameYear(new DateTime(1900,1,1)))
            {
                avglist = this._deviceDB.vStatisticsData.Where(x => x.activePower > 0 && x.statisticsDataDate <= date && x.statisticsDataDate.Year == date.Year);
            }
            else
            {
                avglist = this._deviceDB.vStatisticsData.Where(x => x.activePower > 0);
            }
            var list = await avglist
                .GroupBy(x => new 
                                {x.statisticsStation_powerStationId_fk,
                                 x.deviceGroup })
                .Select(group => new StationDual
                                {
                                    powerStationId = group.Key.statisticsStation_powerStationId_fk,
                                    group = group.Key.deviceGroup,
                                    powerRate = group.Average(data => data.activePower)
                                }).ToListAsync();
            
            decimal ActivePower = list.Sum(x=>x.powerRate);
            return ActivePower;
        }

        private async Task<decimal> InstallData(long powerStationId) {
            if (powerStationId == 0)
            {
                var install = await this._deviceDB.tStatisticsSingleData.Where(x => !x.deviceGroup.Contains("public")).SumAsync(group => group.installed);
                return install;
            }
            var list = this._deviceDB.tStatisticsSingleData.Where(x=>x.powerStation_SingleData_powerStationId_fk == powerStationId);
            if (list.Count() != 0)
            {
                var install = await list.SumAsync(group => group.installed);
                return install;
            }
            else
            {
                return 0;
            }
        }

        private async Task<decimal> yearstdayPower(DateTime date,long powerstationid)
        {
            var daylist = this._deviceDB.tStatisticsData.Where(x=>x.statisticsDataDate.Date.IsSameDay(date));
            return 0;
        }

        private class StationDual
        {
            public long powerStationId { get; set; }
            public decimal powerRate { get; set; }
            public string group { get; set; }
        }
    }
}
